//
//  PersonalCenterViewController.m
//  MyNewProject
//
//  Created by apple on 2019/1/27.
//  Copyright © 2019年 sun. All rights reserved.
//
#import "PersonalCenterViewController.h"

#import "MoneyStateCell.h"
#import "MyOrderCell.h"
#import "MyOrderViewController.h"
#import "SetUpViewController.h"

#import "XMRechargeViewController.h"
#import "QrChargeVC.h"

#import "XMApplicationForCashViewController.h"
#import "XMAccountDetailViewController.h"
#import "HelpingCenterVC.h"
#import "MyPromoCodeVC.h"
#import "MyBillingVC.h"
#import "MyPersonInfoVC.h"
#import "LoginViewController.h"
#import "YPLoginBaseClass.h"

#import "WithDrawCashViewController.h"
//static CGFloat const HeaderImageViewHeight = 200 + SKStatusBar_Height;

@interface PersonalCenterViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView * myTalbleView;
@property(nonatomic,strong)UIButton * headBtn;

@property(nonatomic,assign)CGFloat headImageViewHeight;

@property(nonatomic,strong)UIImageView * headImageView;

@end

@implementation PersonalCenterViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
//    self.headImageViewHeight = 200 + SKStatusBar_Height;
//    [self obtainUserInfo];
    
}
-(void)obtainUserInfo
{
    
    if (IsStrEmpty([UserInfoSingleton shareInstance].userInfo.loginKey)) {
        
        return;
    }
    SKWeakSelf;
    
    [YQNetworking postWithUrl:@"my/getUserInfo" params:@{@"uid":self.uid,@"loginKey":self.loginKey} reloginRefreshBlock:^(id response) {
        
        NSLog(@"-------------");
    } successBlock:^(id response) {
        YPLoginBaseClass * baseLogin = [YPLoginBaseClass modelObjectWithDictionary:response];
        if ([baseLogin.status isEqualToString:@"ok"]) {
            NSDictionary * dic = (NSDictionary *)response;
            SKUserUserDefaults_Save(dic[@"user_info"] , @"UserInfo");
            [UserInfoSingleton shareInstance].userInfo = baseLogin.userInfo;
            [self headerView:YES];
            [weakSelf.myTalbleView reloadData];
        }
    } failBlock:^(NSError *error) {
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    self.gk_navigationBar.hidden = YES;
//    self.headImageViewHeight = 200 + SKStatusBar_Height;

    [self.view addSubview:self.myTalbleView];
    SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
    if (SKUserUserDefaults_Get(@"UserInfo")) {
//        [self headerView:YES];
    }
    else
    {
//        [self headerView:NO];
    }
}
-(void)UserLogOutDeal:(NSNotification *)notification
{
    [self headerView:NO];
    [self.myTalbleView reloadData];
}
-(UITableView*)myTalbleView
{
    if (_myTalbleView ==nil) {
        _myTalbleView =[[UITableView alloc] initWithFrame:CGRectMake(0,0 ,SCREEN_WIDTH , SCREENH_HEIGHT-SKBottomSafe_Height-SKTabbarHeight) style:UITableViewStyleGrouped];
        _myTalbleView.dataSource = self;
        _myTalbleView.delegate = self;
        _myTalbleView.estimatedRowHeight = 0;
        _myTalbleView.estimatedSectionFooterHeight = 0;
        _myTalbleView.estimatedSectionHeaderHeight = 0;
        _myTalbleView.separatorStyle = UITableViewCellSeparatorStyleNone;
        if (@available(iOS 11.0, *)) {
            _myTalbleView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        } else {
            self.automaticallyAdjustsScrollViewInsets = NO;
        }
    }
    return _myTalbleView;
}
#pragma mark --- 头像
-(UIImageView *)headerView:(BOOL)isLogin {
    for (id view  in self.headImageView.subviews) {
        [view removeFromSuperview];
    }
    self.headImageView = nil;
    UIImageView * bgImageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, -(200 + SKStatusBar_Height), SCREEN_WIDTH, self.headImageViewHeight)];
    bgImageView.image =SKIMAGE_NAMED(@"myBgView");
    bgImageView.userInteractionEnabled = YES;
    if (isLogin) {
        UIButton * headBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        
        headBtn.frame = CGRectMake(0, 0, 120, 100);
        headBtn.center = CGPointMake(SCREEN_WIDTH/2, bgImageView.height/2+20);
        
        [headBtn addTarget:self action:@selector(headEvent:) forControlEvents:UIControlEventTouchUpInside];
        headBtn.backgroundColor = [UIColor clearColor];
        
        UIImageView * headImageView =[[UIImageView alloc] initWithFrame:CGRectMake((headBtn.width - 60)/2, 10, 60, 60)];
        [headImageView sd_setImageWithURL:[NSURL URLWithString:SafeString([UserInfoSingleton shareInstance].userInfo.head_url)] placeholderImage:SKIMAGE_NAMED(@"DefaultHead")];
        headImageView.layer.cornerRadius = headImageView.height/2;
        headImageView.layer.masksToBounds = YES;
        [headBtn addSubview:headImageView];
        
        [bgImageView addSubview:headBtn];
        
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, headImageView.bottom + 5, headBtn.width, 20)];
        label.textColor = SKColorWithHex(0x000000);
        label.font = [UIFont systemFontOfSize:16.0f];
        label.textAlignment = NSTextAlignmentCenter;
        label.lineBreakMode =  NSLineBreakByTruncatingTail;
        label.text = SafeString([UserInfoSingleton shareInstance].userInfo.nickname);
        
        [headBtn addSubview:label];
        self.headBtn = headBtn;
    }
    else
    {
        
        UIButton * loginBtn =[UIButton buttonWithType:UIButtonTypeCustom];
        
        loginBtn.frame = CGRectMake(0, 0, 120, 40);
        loginBtn.center = CGPointMake(SCREEN_WIDTH/2, bgImageView.height/2 +20);
        loginBtn.backgroundColor = SKColorWithHex(0x7ab801);
        loginBtn.layer.cornerRadius = loginBtn.height/2;
        loginBtn.layer.masksToBounds = YES;
        
        [loginBtn addTarget:self action:@selector(loginBtnEvent:) forControlEvents:UIControlEventTouchUpInside];
        [loginBtn setTitle:@"登录/注册" forState:UIControlStateNormal];
        [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [bgImageView addSubview:loginBtn];
        self.headBtn = loginBtn;

    }
    self.headImageView = bgImageView;
    self.myTalbleView.contentInset = UIEdgeInsetsMake(self.headImageViewHeight, 0, 0, 0);
    [self.myTalbleView addSubview:self.headImageView];
    return bgImageView;
}

#pragma mark -- 点击头像
-(void)headEvent:(UIButton *)sender
{
    MyPersonInfoVC * myPersionInfoVC =[MyPersonInfoVC new];
    [self.navigationController pushViewController:myPersionInfoVC animated:YES];
}
#pragma mark --点击登录
-(void)loginBtnEvent:(UIButton*)sender {
    NSLog(@"mark --点击登录");
    LoginViewController * loginVC =[[LoginViewController alloc] init];
    SKWeakSelf;
    loginVC.myLoginResult = ^(id model) {
        [weakSelf headerView:YES];
    };
    [self.navigationController pushViewController:loginVC animated:YES];
}
#pragma mark -  UITableView 代理相关

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section>1) {
        return 3;
    }
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        MoneyStateCell * cell =[tableView dequeueReusableCellWithIdentifier:@"MoneyStateCell"];
        if (!cell) {
            cell = [[MoneyStateCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MoneyStateCell"];
        }
        cell.model = nil;
        __weak typeof(self)weakSelf = self;
        cell.myEventBlock = ^(id model, NSInteger eventId) {
            SKLog(@"%ld",(long)eventId);
            //            TODO: 0  提现   1 充值
            switch (eventId) {
                case 0: {
                    SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
                    if (SKUserUserDefaults_Get(@"UserInfo")) {
//                        XMApplicationForCashViewController * afCash = [[XMApplicationForCashViewController alloc]init];
//                        [weakSelf.navigationController pushViewController:afCash animated:YES];
                        if (!IsStrEmpty([UserInfoSingleton shareInstance].userInfo.name)&&!IsStrEmpty([UserInfoSingleton shareInstance].userInfo.card)) {
                            //        button.enabled = NO;
                            WithDrawCashViewController * afCash = [[WithDrawCashViewController alloc]init];
                            [weakSelf.navigationController pushViewController:afCash animated:YES];
                        }
                        else {
                            [self.view makeToast:@"请先去实名认证" duration:1 position:CSToastPositionCenter];
                        }
                    }
                    else {
                        [weakSelf loginBtnEvent:nil];
                    }
                }
                    break;
                case 1: {
                    SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
                    if (SKUserUserDefaults_Get(@"UserInfo")) {
//                        XMRechargeViewController * recharge = [[XMRechargeViewController alloc]init];
                        QrChargeVC * recharge = [QrChargeVC new];

                        [weakSelf.navigationController pushViewController:recharge animated:YES];
                    }
                    else
                    {
                        [weakSelf loginBtnEvent:nil];
                    }
                  
                }
                    break;
              
                default:
                    break;
            }
        };
        cell.myDetailBlock = ^(id model) {
            SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
            if (SKUserUserDefaults_Get(@"UserInfo")) {
                //            TODO:查看明细
                MyBillingVC * accD = [[MyBillingVC alloc]init];
                [weakSelf.navigationController pushViewController:accD animated:YES];
            }
            else
            {
                [weakSelf loginBtnEvent:nil];
            }
        };
        return cell;
    }
    else if (indexPath.section == 1)
    {
        MyOrderCell * cell =[tableView dequeueReusableCellWithIdentifier:@"MyOrderCell"];
        if (!cell) {
            cell = [[MyOrderCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MyOrderCell"];
        }
        __weak typeof(self)weakSelf = self;
        cell.myLookMore = ^(id model) {
            //            TODO: 查看更多
            SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
            if (SKUserUserDefaults_Get(@"UserInfo")) {
                MyOrderViewController * myOrderVC = [[MyOrderViewController alloc] init];
                myOrderVC.selectedCondition = 0;
                [weakSelf.navigationController pushViewController:myOrderVC animated:YES];
                
                SKLog(@"查看更多");
            }
            else {
                [weakSelf loginBtnEvent:nil];
            }
        };
        cell.myEventBlock = ^(id model, NSInteger eventId) {
            SKLog(@"%ld",(long)eventId);
            SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
            if (SKUserUserDefaults_Get(@"UserInfo")) {
                MyOrderViewController * myOrderVC = [[MyOrderViewController alloc] init];
                myOrderVC.selectedCondition = (int)eventId;
                //            myOrderVC.gk_navigationBar.hidden = NO;
                [weakSelf.navigationController pushViewController:myOrderVC animated:YES];
            }
            else {
                [weakSelf loginBtnEvent:nil];
            }
        };
        return cell;
    }
    else {
        UITableViewCell * cell =[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"UITableViewCell"];
        }
        for (id view in [cell.contentView subviews])
        {
            [view removeFromSuperview];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(25, 0, 200, 44)];
        label.textColor = SKColorWithHex(0x444444);
        label.font = SKFONT_Medium(15.0f);
        label.textAlignment = NSTextAlignmentLeft;

        if (indexPath.row == 0) {
            label.text = @"我的推广码";
        }
        else if(indexPath.row == 1){
            label.text = @"帮助中心";
        }
        else{
            label.text = @"设置";
        }
        [cell.contentView addSubview:label];
        
        UIImageView * arrowImageView =[[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH -15 -6, (44-11)/2, 6, 11)];
        arrowImageView.image = SKIMAGE_NAMED(@"rightArrow");
        [cell.contentView addSubview:arrowImageView];
        
        if (indexPath.row <2) {
            UIImageView * imageView =[[UIImageView alloc] initWithFrame:CGRectMake(0, 43.5, SCREEN_WIDTH, 0.5)];
            imageView.backgroundColor =SKRGBColor(237, 237, 237);
            [cell.contentView addSubview:imageView];
        }
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        
        return 40 +10 + 50 + 60-8 ;
    }
    else if (indexPath.section == 1)
    {
        return 130;
    }
    return 44;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return CGFLOAT_MIN;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10;
//    return CGFLOAT_MIN;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section ==2) {
        switch (indexPath.row) {
            case 0: {
                SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
                if (SKUserUserDefaults_Get(@"UserInfo")) {
                    MyPromoCodeVC * helpingVC = [MyPromoCodeVC new];
                    [self.navigationController pushViewController:helpingVC animated:YES];
                }
                else {
                    [self loginBtnEvent:nil];
                }
            }
                break;
            case 1: {
                HelpingCenterVC * helpingVC = [HelpingCenterVC new];
                [self.navigationController pushViewController:helpingVC animated:YES];
            }
                break;
            case 2: {
#pragma mark -  点击设置
                SKAdd_Observer(@"UserLogOut", self,UserLogOutDeal:, nil);
                if (SKUserUserDefaults_Get(@"UserInfo")) {
                    SetUpViewController * setUpVC =[SetUpViewController new];
                    [self.navigationController pushViewController:setUpVC animated:YES];
                }
                else {
                    [self loginBtnEvent:nil];
                }
            }
                break;
            default:
                break;
        }
        NSLog(@"---%ld------",(long)indexPath.row);
    }
    
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {

    CGFloat contentOffsetY = scrollView.contentOffset.y;
    //吸顶临界点(此时的临界点不是视觉感官上导航栏的底部，而是当前屏幕的顶部相对scrollViewContentView的位置)
//    NSLog(@"%f-----------%f----",contentOffsetY,self.headImageViewHeight);
    if(contentOffsetY <= -self.headImageViewHeight) {
        CGRect f = self.headImageView.frame;
        //改变HeadImageView的frame
        //上下放大
        f.origin.y = contentOffsetY;
        f.size.height = -contentOffsetY;
        //左右放大
        f.origin.x = (contentOffsetY * SCREEN_WIDTH / self.headImageViewHeight + SCREEN_WIDTH) / 2;
        f.size.width = -contentOffsetY * SCREEN_WIDTH / self.headImageViewHeight;
        
        //改变头部视图的frame
        self.headImageView.frame = f;
        self.headBtn.center = CGPointMake(self.headImageView.width/2, self.headImageView.height/2 +20);

    }
}
-(void)dealloc
{
    SKRemove_Observer(@"UserLogOut");
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
